import os
import sys
import subprocess
from multiprocessing import Pool
import shutil
import argparse
import re



def run_command(command):
    print(f"Running command: {command}")
    subprocess.run(command, shell=True)

def process_yuv_file(yuv_png_pair):
    """处理单个YUV文件的函数"""
    yuv_path, png_path = yuv_png_pair
    command = f"yuv_player.bat {yuv_path} -o {png_path}"
    success = run_command(command)
    if success:
        print(f"成功转换: {yuv_path} -> {png_path}")
    else:
        print(f"转换失败: {yuv_path}")
    return success
def remove_suffix_files(dir, suffix):
    for filename in os.listdir(dir):
        if filename.endswith(suffix):
            os.remove(os.path.join(dir, filename))

def get_rect_from_file(file_path):
    try:
        with open(file_path, 'r') as f:
            txt = f.read().strip()
            # 分割字符串并转换为int
            rect_values = [int(x.strip()) for x in txt.split(',')]
            # 确保有4个值
            if len(rect_values) != 4:
                raise ValueError(f"Expected 4 values but got {len(rect_values)}")
            return rect_values
    except FileNotFoundError:
        raise FileNotFoundError(f"ROI File not found at path: {file_path}")
    except ValueError as e:
        raise ValueError(f"Invalid value in file: {e}")

def dump_power_log():
    print(f"Dumping power log")
    if os.path.exists('power_log.csv'):
        print('Power log already dumped, skipping dump power log')
    run_command("adb pull /data/syslog/bbklog/power_log")
    csvfiles = py_files = [f for f in os.listdir('power_log') if f.endswith(".csv")]
    if len(csvfiles) == 0:
        raise FileNotFoundError(f"No CSV files found in the power log directory.")
    power_log_file = os.path.join('power_log', csvfiles[0])
    shutil.copy2(power_log_file, "power_log.csv")
    print(f"Dumped power log to power_log.csv")

def dump_pictures(multi_process = False):
    print(f"Dumping pictures multi_process:{multi_process}")
    if os.path.exists('Pictures'):
        print('Pictures folder already exists, skipping dump pictures')
    else:
        run_command("adb pull /sdcard/Pictures")
    yuvs = [f for f in os.listdir('Pictures') if re.match(r"^rgb-(left|right)-[\d._]+yuv$", f)]
    pngs = [f for f in os.listdir('Pictures') if re.match(r"^rgb-(left|right)-[\d._]+png$", f)]
    if len(yuvs) < 2 and len(pngs) < 2:
        raise ValueError(f"Not enough pictures found in Pictures folder")
    print(f"Found {len(yuvs) + len(pngs)} pictures")
    # left
    os.makedirs('left', exist_ok=True)
    run_command(f'chrono_file_selector.bat Pictures/ -p rgb-left- -o left/')
    if len(yuvs) > 2:
        if multi_process:
            run_command(f'yuv_player.bat left/ -o left/ -m')
        else:
            run_command(f'yuv_player.bat left/ -o left/')
        remove_suffix_files('left', '.yuv')
    # right
    os.makedirs('right', exist_ok=True)
    run_command(f'chrono_file_selector.bat Pictures/ -p rgb-right- -o right/')
    if len(yuvs) > 2:
        if multi_process:
            run_command(f'yuv_player.bat right/ -o right/ -m')
        else:
            run_command(f'yuv_player.bat right/ -o right/')
        remove_suffix_files('right', '.yuv')
    print(f"Dumped pictures to left and right folders")

def crop_analysis(multi_process = False):
    print(f"Cropping analysis multi_process:{multi_process}")
    left_roi_config = 'left/roi.txt'
    right_roi_config = 'right/roi.txt'
    left_rect = get_rect_from_file(left_roi_config) 
    right_rect = get_rect_from_file(right_roi_config)
    print(f"Left ROI: {left_rect}, Right ROI: {right_rect}")
    if left_rect is None :
        raise ValueError(f"Left rect is None")
    if right_rect is None :
        raise ValueError(f"Right rect is None")
    if multi_process:
        run_command(f'crop_analysis left -m -o left_analysis -r {left_rect[0]} {left_rect[1]} {left_rect[2]} {left_rect[3]}')
        run_command(f'crop_analysis right -m -o right_analysis -r {right_rect[0]} {right_rect[1]} {right_rect[2]} {right_rect[3]}')
    else:
        run_command(f'crop_analysis left -o left_analysis -r {left_rect[0]} {left_rect[1]} {left_rect[2]} {left_rect[3]}')
        run_command(f'crop_analysis right -o right_analysis -r {right_rect[0]} {right_rect[1]} {right_rect[2]} {right_rect[3]}')
    print(f"Crop analysis done")

def log_merge():
    print(f"Merging logs")
    left_crop_analysis = 'left_analysis/crop_analysis.csv'
    right_crop_analysis = 'right_analysis/crop_analysis.csv'
    power_log = 'power_log.csv'
    if not os.path.exists(power_log):
        raise FileNotFoundError(f"Power log file not found")
    if not os.path.exists(left_crop_analysis):
        raise FileNotFoundError(f"Left analysis file not found")
    if not os.path.exists(right_crop_analysis):
        raise FileNotFoundError(f"Right analysis file not found")
    run_command(f'log_merge {left_crop_analysis} {power_log}')
    run_command(f'log_merge {right_crop_analysis} {power_log}')
    print(f"Logs merged")

def constant_temperature_chat():
    print(f"Constant temperature chat")
    left_merged_log = 'left_analysis/crop_analysis_merged.csv'
    right_merged_log = 'right_analysis/crop_analysis_merged.csv'
    if not os.path.exists(left_merged_log):
        raise FileNotFoundError(f"Left merged log file not found")
    if not os.path.exists(right_merged_log):
        raise FileNotFoundError(f"Right merged log file not found")
    # get current folder name
    current_folder = os.path.basename(os.getcwd())
    run_command(f'line_plotter.bat {left_merged_log}  -xf none -xd none -x minute -y VST1_T_sensor Y_std attenuation -f left-{current_folder} -o ./')
    run_command(f'line_plotter.bat {right_merged_log}  -xf none -xd none -x minute -y VST2_T_sensor Y_std attenuation -f right-{current_folder} -o ./')
    print(f"Constant temperature chat done")

def main():

    if  len(sys.argv) > 1:
        cwp = sys.argv[1]
        os.chdir(cwp)
        multi_process = False
    else:
        multi_process = True
    dump_pictures(multi_process)
    dump_power_log()
    crop_analysis(multi_process)
    log_merge()
    constant_temperature_chat()


if __name__ == "__main__":
    main()
